package lib.self.util.encrypt;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import lib.self.utils.BaseDataUtil;
import lib.self.utils.TextUtil;

/**
 * description: Aes Cbc 加密工具类
 * author: Steven Xiao
 * date: 2017/5/25
 */
public class AesCbcUtil {
    private static final String TAG = AesCbcUtil.class.getSimpleName();

    public static final String KEncodingFormat = "utf-8";
    public static final String KASCII = "ASCII";
    public static final String KAES = "AES";
    private static final String KRules = "AES/CBC/PKCS5Padding";

    /**
     * 加密
     *
     * @param text 加密内容
     * @param key
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     */
    public static String getEncrypt(String text, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(KRules);
        byte[] raw = key.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KAES);
        String iv = TextUtil.getReversString(key);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(text.getBytes(KEncodingFormat));
        return BaseDataUtil.bytesToHexString(encrypted);
    }

    /**
     * 解密
     *
     * @param encrypt
     * @param key
     * @return
     * @throws Exception
     */
    public static String getDecrypt(String encrypt, String key) throws Exception {
        byte[] raw = key.getBytes(KASCII);
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, KAES);
        Cipher cipher = Cipher.getInstance(KRules);
        String iv = TextUtil.getReversString(key);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted1 = BaseDataUtil.hexStringToBytes(encrypt);//先用base64解密
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original, KEncodingFormat);
        return originalString;
    }
}
